package me.zingon.webmvc.servlet;

import me.zingon.core.context.SummerContext;
import me.zingon.core.context.annotation.SController;
import me.zingon.core.context.annotation.SRequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SummerHandlerMapping {

    SummerContext context;
    Map<String, SummerHandler> handlerMappings = new ConcurrentHashMap<>(256);

    public SummerHandlerMapping(SummerContext context) {
        this.context = context;
        init();
    }

    SummerHandler getHandler(HttpServletRequest request) {
        return handlerMappings.get(request.getRequestURI().replace(request.getContextPath(),""));
    }

    void init() {
        List<Object> controller = context.getController();
        controller.stream().forEach(item -> {
            SRequestMapping sController = item.getClass().getAnnotation(SRequestMapping.class);
            String path = sController.value();
            Method[] methods = item.getClass().getDeclaredMethods();
            for (int i = methods.length - 1; i >= 0; i--) {
                SRequestMapping requestMapping = methods[i].getAnnotation(SRequestMapping.class);
                if(requestMapping == null){
                    continue;
                }
                handlerMappings.put(path+requestMapping.value(),new SummerHandler(item,methods[i]));
            }
        });
    }


}
